package com.zhaoc.web.action;

import com.opensymphony.xwork2.ActionContext;
import com.zhaoc.domain.system.User;
import com.zhaoc.service.IUserService;
import com.zhaoc.web.base.BaseAction;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <p>title:com.zhaoc.web.action</p>
 * date:2018/8/21 0021
 * time:10:18
 * author:赵成
 * user:13566
 */
@ParentPackage("json-default")
public class UserAction extends BaseAction<User> {

    @Autowired
    private IUserService userService;

    //用户登陆
    @Action(value = "user_login", results = {@Result(name = SUCCESS, type = "redirect", location = "index.html"),
            @Result(name = LOGIN, type = "redirect", location = "login.html")})
    public String login() {
        //基于shiro实现用户登陆
        Subject subject = SecurityUtils.getSubject();
        //用户名和密码信息都要存入token中
        AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
        try {
            //调用shiro自带的登陆验证
            subject.login(token);
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            //登陆失败
            return LOGIN;
        }
    }

    //用户退出登陆
    @Action(value = "user_logout",results = {@Result(name = SUCCESS,type = "redirect",location = "login.html")})
    public String logout(){
        //基于shiro完成退出登陆
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return SUCCESS;
    }

    //查询所有用户
    @Action(value = "user_list",results = {@Result(name = SUCCESS,type = "json")})
    public String list(){
        List<User> users = userService.findAll();

        ActionContext.getContext().getValueStack().push(users);

        return SUCCESS;
    }


    private String[] roleId;

    public void setRoleId(String[] roleId) {
        this.roleId = roleId;
    }

    //添加用户
    @Action(value = "user_save",results = {@Result(name = SUCCESS,type = "redirect",location = "pages/system/userlist.html")})
    public String save(){
        userService.save(model,roleId);
        return SUCCESS;
    }
}
